// 顶点着色器程序
var VSHADER_SOURCE =
	'attribute vec4 a_Position;\n' +
	'attribute float a_PointSize;\n' +
	'void main() {\n' +
	' gl_Position = a_Position;\n' + // 设置坐标
	' gl_PointSize = a_PointSize;\n' + // 尺寸
	'}\n';

// 片元着色器程序
var FSHADER_SOURCE =
	'void main() {\n' +
	' gl_FragColor = vec4(0.1,1.0,0.2,0.4);\n' +
	'}\n';

function main() {
	// 获取 canvas 元素
	var canvas = document.getElementById('webgl');

	// 获取 WebGL 绘图上下文
	var gl = getWebGLContext(canvas, true);
	if(!gl) {
		console.log('Failed to get the rendering content of WebGL');
		return;
	}
	//初始着色器
	if(!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
		console.log('Failed to initialize shaders.');
		return;
	}
	// 获取 attribute 变量的存储位置
	var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
	if(a_Position < 0) {
		console.log('Failed to get the storage location of a_Position');
		return;
	}
	var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
	// 将顶点位置传输给attribute变量
	//gl.vertexAttrib3f(a_Position, 0.0, 0.0, 0.0);
	canvas.onmousedown = function(event) {
		click(event, gl, canvas, a_Position);
	};
	gl.vertexAttrib1f(a_PointSize, 30.0);

	//设置 <canvas> 背景色
	gl.clearColor(0.0, 0.0, 0.0, 1.0);
	// 清空 <canvas>
	gl.clear(gl.COLOR_BUFFER_BIT);

	// 绘制一个点
	//gl.drawArrays(gl.POINTS, 0, 1);
}

var g_points = [];

function click(event, gl, canvas, a_Position) {

	var x = event.clientX;
	var y = event.clientY;
	var rect = event.target.getBoundingClientRect();
	x = ((x - rect.left) - canvas.height / 2) / (canvas.height / 2);
	y = (canvas.width / 2 - (y - rect.top)) / (canvas.width / 2);

	g_points.push([x, y]);

	// 清空 <canvas>
	gl.clear(gl.COLOR_BUFFER_BIT);
	var len = g_points.length;
	for(var i = 0; i < len; i++) {
		var xy = g_points[i];
		gl.vertexAttrib3f(a_Position, xy[0], xy[1], 0.0);

		// 绘制点
		gl.drawArrays(gl.POINTS, 0, 1);
	}
}